package com.ruoyi.syf.handler.task;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 隐患排查定时任务上下文对象
 *
 * @author yr
 * @date 2024-07-31
 */
@Service
public class TaskFactory {

    private final Map<String, TaskStrategy> map = new ConcurrentHashMap<>();

    @Autowired
    private ApplicationContext applicationContext;

    @PostConstruct
    private void init(){
        Map<String, TaskStrategy> beansOfType = applicationContext.getBeansOfType(TaskStrategy.class);
        beansOfType.forEach((k,v) -> {
            map.put(v.getTaskType(),v);
        });
    }

    /**
     * 转cron表达式
     */
    public String toCronExpression(String taskType,int num, String timeUnit, Date startTime) throws IllegalAccessException {
        return map.get(taskType).toCronExpression(num,timeUnit,startTime);
    }

    /**
     * 计算下一周期开始时间
     */
    public Date getNextBeginTime(String taskType,Date date, Date startTime, Integer cycle, String cycleUnit) throws IllegalAccessException {
        return map.get(taskType).getNextBeginTime(date,startTime,cycle,cycleUnit);
    }

    /**
     * 计算上一周期开始时间
     */
    public Date getLastBeginTime(String taskType,Date startTime, Integer cycle, String cycleUnit) throws IllegalAccessException {
        return map.get(taskType).getLastBeginTime(startTime,cycle,cycleUnit);
    }

    /**
     * 计算离当前最近的一期定时任务执行时间
     */
    public Date getRecentBeginTime(String taskType,Date lastBeginTime, Integer cycle, String cycleUnit) throws IllegalAccessException {
        return map.get(taskType).getRecentBeginTime(lastBeginTime,cycle,cycleUnit);
    }

}
